using System.Collections;
using UnityEngine;

public class BlinkController : MonoBehaviour
{
    public SkinnedMeshRenderer skinnedMeshRenderer;
    public int blinkBlendIndex; // 闪烁对应的BlendShapes的索引
    public float blinkWeight = 0.0f; // 闪烁的起始权重值
    public float blinkDuration = 0.2f; // 闪烁闭合或张开所用的时间
    public float blinkInterval = 3.0f; // 每次闪烁之间的间隔时间

    private float blinkTimer = 0.0f; // 计时器，用于控制闪烁间隔

    void Start()
    {
        // 设置初始权重
        skinnedMeshRenderer.SetBlendShapeWeight(blinkBlendIndex, blinkWeight);
    }

    void Update()
    {
        blinkTimer += Time.deltaTime;

        // 如果达到闪烁间隔时间，执行闪烁
        if (blinkTimer >= blinkInterval)
        {
            StartCoroutine(BlinkCoroutine());
            blinkTimer = 0.0f; // 重置计时器
        }
    }

    IEnumerator BlinkCoroutine()
    {
        // 闭眼：从起始值渐变到100
        for (float t = 0.0f; t < blinkDuration; t += Time.deltaTime)
        {
            float weight = Mathf.Lerp(blinkWeight, 100.0f, t / blinkDuration);
            skinnedMeshRenderer.SetBlendShapeWeight(blinkBlendIndex, weight);
            yield return null;
        }

        // 睁眼：从100渐变回起始值
        for (float t = 0.0f; t < blinkDuration; t += Time.deltaTime)
        {
            float weight = Mathf.Lerp(100.0f, blinkWeight, t / blinkDuration);
            skinnedMeshRenderer.SetBlendShapeWeight(blinkBlendIndex, weight);
            yield return null;
        }

        // 恢复为初始值，确保数值精确
        skinnedMeshRenderer.SetBlendShapeWeight(blinkBlendIndex, blinkWeight);
    }
}